<?php
namespace app\wxwork\logic;
/**
 * 企业微信的基础功能
 * 获取token
 * 发送请求
 * 接收回调
 */
class WXWork
{
    protected $error="";
    public function getError()
    {
        return $this->error;
    }

    public $corpID;//公司id
    public $agentID;//应用id
    public $secret;//应用密钥
    public $host="https://qyapi.weixin.qq.com/cgi-bin/";
    function __construct(){
        $this->corpID=config("wxwork_corpID");
        $this->agentID=config("wxwork_agentId");
        $this->secret=config("wxwork_secret");
    }
    public function getToken(){
        $token=cache("wxwork_token");
        if($token){
            return $token;
        }
        $url=$this->host."gettoken?corpid=".$this->corpID."&corpsecret=".$this->secret;
        $response=$this->get($url);
        if($response===false){
            return false;
        }
        cache("wxwork_token",$response["access_token"],$response["expires_in"]);
        return $response["access_token"];
    }
    public function get($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        if(!$output){
            $this->error="curl error:".curl_errno($ch)." message:".curl_error($ch);
            return false;
        }
        return $this->parseData($output);
    }
    public function post($url,$data){
        $data=json_encode($data);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        if(!$output){
            $this->error="curl error:".curl_errno($ch)." message:".curl_error($ch);
            return false;
        }
        return $this->parseData($output);
    }
    public function parseData($output){
        $response=json_decode($output,true);
        if($response["errcode"]!==0){
            $this->error=$response["errmsg"];
            return false;
        }
        return $response;
    }
}
